package com.yhd.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.yhd.entity.*;
import com.yhd.entity.dto.*;
import com.yhd.entity.query.*;
import com.yhd.entity.result.ResultVo;
import com.yhd.entity.wx.WxPayResult;
import com.yhd.enums.CourseDetailTypeEnum;
import com.yhd.mapper.*;
import com.yhd.model.PageInfo;
import com.yhd.model.ResultPage;
import com.yhd.service.*;
import com.yhd.utils.BeanMapperUtil;
import com.yhd.utils.ImageUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

@Transactional(rollbackFor = Exception.class)
@Service
public class CourseServiceImpl extends BaseService<CourseMapper, TCourse> implements CourseService {
	@Autowired
	private CourseMapper courseMapper;
	@Autowired
	private CourseDetailMapper courseDetailMapper;
	@Autowired
	private CourseDetailService courseDetailService;
	@Autowired
	private UserService userService;
	@Autowired
	private CourseBookedMapper courseBookedMapper;
	@Autowired
	private CorporateService corporateService;
	@Autowired
	private CourseBookedService courseBookedService;
	@Autowired
	private SysDictService sysDictService;
	@Autowired
	private WxPayService wxPayService;
	@Autowired
	private CourseCollectionMapper courseCollectionMapper;
	@Autowired
	private CourseAboutMapper courseAboutMapper;
	@Autowired
	private CourseScheduleDetailMapper courseScheduleDetailMapper;
	@Autowired
	private BrowseRecordMapper browseRecordMapper;
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private SysDictMapper dictMapper;

	private final static Logger logger = LoggerFactory.getLogger(CourseServiceImpl.class);


	private List<CourseDto> getCourseDtos(List<TCourse> courses) {
        List<CourseDto> result = new ArrayList<>();
        if (!CollectionUtils.isEmpty(courses)) {
            result = BeanMapperUtil.copyList(courses, CourseDto.class);

            result = result.stream().map(courseDto -> {
//	            courseDto.setTitle(null);
                courseDto.setContent(null);

                // 获取分类名称
			    TSystemDictionary systemDictionary = dictMapper.selectSysDictInfo(courseDto.getClassifyId());
			    courseDto.setClassifyName(systemDictionary.getName());
                // 获取师资信息
				List<CourseDto> teamList = courseMapper.selectTeam(courseDto.getId());
				if (null != teamList && teamList.size() > 0) {
					courseDto.setTeamDto(teamList.get(0));
				}
                return courseDto;
            }).collect(Collectors.toList());
        }
        return result;
    }

	/**
	 * 课程列表分页查询
	 * @param courseVO
	 * @return
	 */
	@Override
    public ResultPage<List<CourseDto>> selectCourseList(CourseVO courseVO) {
        PageInfo pageInfo = new PageInfo();
        pageInfo.setPageNum(courseVO.getPageNum());
        pageInfo.setPageSize(courseVO.getPageSize());
        Page<List<CourseDto>> reslut = pageBuild(pageInfo).doSelectPage(()->{
            List<CourseDto> list = courseMapper.selectCourseList(courseVO);
			for (CourseDto courseDto:list) {
				// 返回活动关联的课程
				if (null != courseDto.getType() && courseDto.getType().equals("activity")){
					List<CourseDto> courseDtoList = courseMapper.selectActityCourseList(courseDto.getId());
					if (null != courseDtoList && courseDtoList.size() > 0){
						courseDto.setCourseDtoList(courseDtoList);
					}
				}
				// 返回课程/活动关联的师资
				if(null != courseDto.getType() && (courseDto.getType().equals("course") || courseDto.getType().equals("activity"))) {
					List<CourseDto> teamList = courseMapper.selectTeam(courseDto.getId());
					if (null != teamList && teamList.size() > 0){
						courseDto.setTeamDto(teamList.get(0));
					}
				}

				courseDto.setOtherNum(courseMapper.getOtherNumByType(courseDto.getType(),courseDto.getId()));
				courseDto.setPayNum(courseMapper.getPayNumByType(courseDto.getType(),courseDto.getId()));
			}
        });
        return pageTransform(reslut);
    }

	/**
	 * 查询活动详情
	 * @param courseVO
	 * @return
	 */
	@Override
	public CourseDto selectCourseInfo(CourseVO courseVO) {
		CourseDto courseDto = courseMapper.selectCourseInfo(courseVO);
		if (null != courseDto){
			if (null != courseDto.getType() && courseDto.getType().equals("activity")){
				List<CourseDto> courseDtoList = courseMapper.selectActityCourseList(courseDto.getId());
				if (null != courseDtoList && courseDtoList.size() > 0){
					courseDto.setCourseDtoList(courseDtoList);
				}
			}

			// 返回课程/活动关联的师资
			List<CourseDto> teamList = courseMapper.selectTeam(courseDto.getId());
			if (null != teamList && teamList.size() > 0){
				courseDto.setTeamDto(teamList.get(0));
			}
		}
		return courseDto;
	}


	/**
	 * 创建课程/活动/师资
	 * @param courseVO
	 * @param userDto
	 * @return
	 */
	@Override
	public CourseDto addCourse(CourseVO courseVO, UserDto userDto) {
		TCourse tCourse = new TCourse();
		if (null != courseVO) {
			BeanUtils.copyProperties(courseVO, tCourse);
			tCourse.setCreateTime(new Date());
			tCourse.setCreateUserId(userDto.getId());
			tCourse.setUpdateTime(new Date());
			tCourse.setUpdateUserId(userDto.getId());
			int addCourse = courseMapper.insertSelective(tCourse);
			if (addCourse > 0) {
				// 活动关联课程
				if (courseVO.getType().equals("activity") && null != courseVO.getCourseList() && courseVO.getCourseList().size() > 0){
					for (CourseVO newCourseVO:courseVO.getCourseList()) {
						TCourseDetail newTCourseDetail = new TCourseDetail();
						// 关联活动ID
						newTCourseDetail.setCourseId(tCourse.getId());
						// 关联课程原始ID
						newTCourseDetail.setCode(newCourseVO.getId()+"");
						newTCourseDetail.setType("course");
						newTCourseDetail.setCreateTime(new Date());
						newTCourseDetail.setCreateUserId(userDto.getId());
						int newAddCourseDetail = courseDetailMapper.insertSelective(newTCourseDetail);
					}
				}

				// 活动｜课程关联师资
				if ((courseVO.getType().equals("course") || courseVO.getType().equals("activity")) && null!= courseVO.getTeamId() && courseVO.getTeamId() > 0){
					TCourseDetail newTeamDetail = new TCourseDetail();
					// 关联活动ID
					newTeamDetail.setCourseId(tCourse.getId());
					// 关联师资原始ID
					newTeamDetail.setCode(courseVO.getTeamId()+"");
					newTeamDetail.setType("team");
					newTeamDetail.setCreateTime(new Date());
					newTeamDetail.setCreateUserId(userDto.getId());
					int newAddCourseDetail = courseDetailMapper.insertSelective(newTeamDetail);

				}

				CourseDto courseDto = new CourseDto();
				BeanUtils.copyProperties(tCourse, courseDto);
				return courseDto;
			}
		}
		return null;
	}

	@Override
	public ResultPage<List<CourseDto>> getCourseList(String type, Integer pageNum, Integer pageSize) {
		PageInfo pageInfo = new PageInfo();
		pageInfo.setPageNum(pageNum == null ? 1 : pageNum);
		pageInfo.setPageSize(pageSize == null ? 10 : pageSize);
		Example example = new Example(TCourse.class);
		Example.Criteria criteria = example.createCriteria().andEqualTo("type", type)
				.andEqualTo("isDel",0).andEqualTo("status",1);
		example.setOrderByClause("sort asc");
		Page<List<TCourse>> result = pageBuild(pageInfo).doSelectPage(() -> {
			courseMapper.selectByExample(example);
		});
		ResultPage resultPage = pageTransform(result);
		if (CollectionUtils.isEmpty(resultPage.getData())) {
			return resultPage;
		}
		List<TCourse> data = resultPage.getData();
		resultPage.setData(this.getCourseDtos(data));
		return resultPage;
	}
	
	/**
	 * 课程详情
	 * @param courseId
	 * @param userInfo
	 * @return
	 */
	@Override
	public CourseDto courseDetail(Integer courseId, UserDto userInfo) {
		CourseDto result = this.detail(courseId, userInfo);
		if (userInfo != null){
			//预约信息列表
			TCourseAbout about = new TCourseAbout();
			about.setUserId(userInfo.getId());
			about.setCourseId(courseId);
			List<TCourseAbout> abouts = courseAboutMapper.select(about);
			result.setAboutDtos(BeanMapperUtil.copyList(abouts, CourseAboutDto.class));
		}
		return result;
	}
	
	/**
	 * 查询活动列表
	 * @param name
	 * @param classifyId
	 * @param pageSize
	 * @param pageNum
	 * @return
	 */
	@Override
	public ResultPage<List<CourseDto>> getActivityList(String name, Integer activityStatus, String classifyId, Integer pageSize, Integer pageNum, String startTime, String endTime) {
		PageInfo pageInfo = new PageInfo();
		pageInfo.setPageNum(pageNum == null ? 1 : pageNum);
		pageInfo.setPageSize(pageSize == null ? 10 : pageSize);
		Example example = new Example(TCourse.class);
		Example.Criteria criteria = example.createCriteria().andEqualTo("type", "activity");
		if (!StringUtils.isEmpty(name)) {
			criteria.andLike("name", "%" + name + "%");
		}
//		if (activityStatus != null) {
//			if (activityStatus == 0) {
//				//未开始
//				criteria.andGreaterThan("sellBeginTime",new Date());
//			} else if (activityStatus == 1) {
//				//进行中
//				criteria.andLessThanOrEqualTo("sellBeginTime", new Date())
//						.andGreaterThanOrEqualTo("sellEndTime",new Date());
//			} else if (activityStatus == 2) {
//				//已结束
//				criteria.andLessThan("sellEndTime",new Date());
//			}
//		}
		if (!StringUtils.isEmpty(classifyId)) {
			criteria.andEqualTo("classifyId",classifyId);
		}

		if (!StringUtils.isEmpty(startTime) && !StringUtils.isEmpty(endTime)) {
			criteria.andLessThanOrEqualTo("sellBeginTime", endTime)
					.andGreaterThanOrEqualTo("sellEndTime", startTime);
		}

//		criteria.andEqualTo("status", 1);
		example.setOrderByClause("sort asc");
		Page<List<TCourse>> result = pageBuild(pageInfo).doSelectPage(() -> {
			courseMapper.selectByExample(example);
		});
		ResultPage resultPage = pageTransform(result);
		if (CollectionUtils.isEmpty(resultPage.getData())) {
			return resultPage;
		}
		List<TCourse> data = resultPage.getData();
		List<CourseDto> courseDtos = getCourseDtos(data);
		courseDtos = courseDtos.stream().map(courseDto -> {
			if (courseDto.getSellBeginTime() != null && courseDto.getSellEndTime() != null) {
				if (new Date().compareTo(courseDto.getSellBeginTime()) < 0) {
					courseDto.setActivityStatus(0);
				} else if (new Date().compareTo(courseDto.getSellBeginTime()) > 0 && new Date().compareTo(courseDto.getSellEndTime()) < 0) {
					courseDto.setActivityStatus(1);
				} else if (new Date().compareTo(courseDto.getSellEndTime()) > 0) {
					courseDto.setActivityStatus(2);
				}
			}
			return courseDto;
		}).collect(Collectors.toList());
		resultPage.setData(courseDtos);
		return resultPage;
	}

	/**
	 * 查询团队列表
	 * @param name
	 * @param classifyId
	 * @param pageSize
	 * @param pageNum
	 * @return
	 */
	@Override
	public ResultPage<List<CourseDto>>getTeamList(String name, String classifyId, Integer pageSize, Integer pageNum) {
		PageInfo pageInfo = new PageInfo();
		pageInfo.setPageNum(pageNum == null ? 1 : pageNum);
		pageInfo.setPageSize(pageSize == null ? 10 : pageSize);
		Example example = new Example(TCourse.class);
		Example.Criteria criteria = example.createCriteria().andEqualTo("type", "team");
		if (!StringUtils.isEmpty(name)) {
			criteria.andLike("name", "%" + name + "%");
		}
		if (!StringUtils.isEmpty(classifyId)) {
			criteria .andEqualTo("classifyId",classifyId);
		}
		criteria.andEqualTo("status", 1);
		example.setOrderByClause("sort asc");
		Page<List<TCourse>> result = pageBuild(pageInfo).doSelectPage(() -> {
			courseMapper.selectByExample(example);
		});
		ResultPage resultPage = pageTransform(result);
		if (CollectionUtils.isEmpty(resultPage.getData())) {
			return resultPage;
		}
//		List<TCourse> data = resultPage.getData();
//		List<CourseDto> courseDtos = getCourseDtos(data);
//		courseDtos = courseDtos.stream().map(courseDto -> {
//			if (courseDto.getSellBeginTime() != null && courseDto.getSellEndTime() != null) {
//				if (new Date().compareTo(courseDto.getSellBeginTime()) < 0) {
//					courseDto.setActivityStatus(0);
//				} else if (new Date().compareTo(courseDto.getSellBeginTime()) > 0 && new Date().compareTo(courseDto.getSellEndTime()) < 0) {
//					courseDto.setActivityStatus(1);
//				} else if (new Date().compareTo(courseDto.getSellEndTime()) > 0) {
//					courseDto.setActivityStatus(2);
//				}
//			}
//			return courseDto;
//		}).collect(Collectors.toList());
//		resultPage.setData(courseDtos);
		return resultPage;
	}

	/**
	 * 下单
	 * @param booked
	 * @param userInfo
	 * @return
	 * @throws Exception
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public ResultVo<CourseBookedDto> order(CourseBookedVO booked, UserDto userInfo) {
		TCourse course = this.selectById(Integer.parseInt(booked.getCourseId()));
		booked.setCreateTime(new Date());
		TCourseBooked courseBooked = new TCourseBooked();
		BeanUtils.copyProperties(booked, courseBooked);
		
		//课程必须是进行中
		if ("activity".equals(courseBooked.getType()) && booked.getSubType() == 0) {
			if (!(new Date().compareTo(course.getSellBeginTime()) > 0 && new Date().compareTo(course.getSellEndTime()) < 0)){
				return ResultVo.failure("10006", "活动不是进行中");
			}
		}
		//校验体验预约
		if (booked.getSubType() == 1 && "course".equals(courseBooked.getType()) && userInfo.getFreeNum() < 1) {
			return  ResultVo.failure("10003","体验预约次数已达上限");
		}
		
		//判断是否有未完成的订单
		CourseBookedDto userCourseBooke = this.courseBookedService.getUserCourseBooke(Integer.parseInt(booked.getCourseId()), userInfo.getId());
		if ( userCourseBooke != null && userCourseBooke.getSubType() != 1) {
			return ResultVo.failure("10006", "有未完成的订单");
		}
		
		//校验库存
		if (booked.getSubType() != 1 && course.getSaleNum() >= course.getLimitStuNum()) {
			return ResultVo.failure("10006", "库存超出限制");
		}
		
		
		//免费报名
		if(booked.getSubType() == 1 && "activity".equals(courseBooked.getType())) {
			//判断是否可以免费报名
			List<TCourseDetail> codeByTypes = courseDetailService.getCodeByType(course.getId(), CourseDetailTypeEnum.COURSE.getType());
			if (CollectionUtils.isEmpty(codeByTypes)) {
				return ResultVo.failure("10003","无法免费报名");
			}
			//获取关联的课程
			TCourseDetail courseDetail = codeByTypes.get(0);
			String code = courseDetail.getCode();
			TCourse tCourse = this.selectById(Integer.parseInt(code));
			//判断是否购买了该课程
			CourseBookedDto courseBooke = courseBookedService.getUserCourseBooke(tCourse.getId(), userInfo.getId());
			if (courseBooke == null || courseBooke.getStatus() != 2){
				return ResultVo.failure("10003","无法免费报名");
			}
		}
		//预约体验直接改成已付款
		courseBooked.setPayType(booked.getSubType() == 1 ? 2 : null);
		courseBooked.setStatus(booked.getSubType() == 1 ? 2 : 0);
		courseBooked.setCuserId(userInfo.getId());
		courseBooked.setCreateTime(new Date());
		CourseBookedDto result = new CourseBookedDto();
		//生产成这边的订单号
		String outOrderId = UUID.randomUUID().toString().replace("-", "");
		courseBooked.setOrderNo(outOrderId);
		courseBooked.setPrice(course.getPrice());
		//后台下单的情况
		if (booked.getSubType() == 3){
			courseBooked.setPayType(2);
			courseBooked.setStatus(2);
			//加销量
			this.addSaleNum(courseBooked);
		}
		if (courseBooked.getStatus() == 2) {
			courseBooked.setPayTime(new Date());
		}
		//活动订单不需要审核
		if ("activity".equals(courseBooked.getType()) && courseBooked.getStatus() == 0) {
			courseBooked.setStatus(1);
		}
		//活动免费报名也要加销量
		if (booked.getSubType() == 1 && "activity".equals(courseBooked.getType())) {
			this.addSaleNum(courseBooked);
		}
		if ("activity".equals(courseBooked.getType())) {
			courseBooked.setSubType(0);
		}
		
		if (courseBooked.getSubType() == 1) {
			//free -1
			UserDto userDto = userService.selectUserById(userInfo.getId());
			UserVO user = new UserVO();
			user.setFreeNum(userDto.getFreeNum() -1);
			userService.updateUser(user, userInfo);
			
		}
		courseBookedMapper.insertSelective(courseBooked);
		BeanUtils.copyProperties(courseBooked, result);
		return ResultVo.success(result);
	}

	private void addSaleNum(TCourseBooked courseBooked) {
		TCourse course = new TCourse();
		course.setId(Integer.parseInt(courseBooked.getCourseId()));
		course = courseMapper.selectByPrimaryKey(course);
		course.setSaleNum(course.getSaleNum() + 1);
		courseMapper.updateByPrimaryKeySelective(course);
	}

	/**
	 * 获取全部课程
	 * @param courseVO
	 * @return
	 */
	@Override
	public List<CourseDto> selectAllCourseList(CourseVO courseVO) {
		return courseMapper.selectAllCourseList(courseVO);
	}

	/**
	 * 所有活动类型
	 * @return
	 */
	@Override
	public List<SystemDictionaryDto> getActivityListClassList() {
		SystemDictionaryVO param = new SystemDictionaryVO();
		param.setGroupId("200");
		return  sysDictService.selectAllClassifyList(param);
	}

	/**
	 * 所有师资类型
	 */
	/**
	 * 所有活动类型
	 * @return
	 */
	@Override
	public List<SystemDictionaryDto> getTeamListClassList() {
		SystemDictionaryVO param = new SystemDictionaryVO();
		param.setGroupId("500");
		return  sysDictService.selectAllClassifyList(param);
	}
	
	/**
	 * 微信下单
	 * @param orderNo
	 * @param userInfo
	 * @return
	 */
	@Override
	public ResultVo<WxPayResult> wxPay(String orderNo, UserDto userInfo) throws Exception {
		TCourseBooked booked = courseBookedService.selectBookeByOrderNo(orderNo);
		if (booked == null) {
			return ResultVo.failure("10006", "订单不存在,或者未审核");
		}
		CourseBookedDto bookedDto = new CourseBookedDto();
		//查询价格
		CourseVO courseVO = new CourseVO();
		courseVO.setId(Integer.parseInt(booked.getCourseId()));
		CourseDto courseDto = this.selectCourseInfo(courseVO);
		
		BeanUtils.copyProperties(booked, bookedDto);
		bookedDto.setPrice(courseDto.getPrice());
		bookedDto.setCourseDto(courseDto);
		Map<String, String> order = null;
		try {
			order = wxPayService.unifiedOrder(bookedDto, userInfo.getOpenId());
		}catch (Exception e){
			return ResultVo.failure("10006", e.getMessage());
		}
		WxPayResult result = new WxPayResult();
		result.setParam(JSON.toJSONString(order));
		return ResultVo.success(result);
	}
	
	/**
	 * 收藏
	 * @param courseVO
	 * @param userInfo
	 * @return
	 */
	@Override
	public CourseDto collect(CourseVO courseVO, UserDto userInfo) {
		TCourse course = this.selectById(courseVO.getId());
		TCourseCollection  collection = this.selectCollect(userInfo.getId(), course.getId(), course.getType());
		if (courseVO.getCollected() == 1 ){
			if (collection == null) {
				//新增收藏
				collection = new TCourseCollection();
				collection.setType(course.getType());
				collection.setUserId(userInfo.getId());
				collection.setCourseId(course.getId());
				collection.setCreateTime(new Date());
				this.courseCollectionMapper.insertSelective(collection);
			}
		}else {
			//取消收藏
			if (collection != null) {
				this.deleteCollection(collection);
			}
		}
		return this.courseDetail(course.getId(), userInfo);
	}

	private void deleteCollection(TCourseCollection collection) {
		if (collection.getUserId() != null && collection.getCourseId() != null) {
			courseCollectionMapper.delete(collection);
		}
	}

	private TCourseCollection selectCollect(String userId, Integer courseId, String type) {
		TCourseCollection collection = new TCourseCollection();
		collection.setCourseId(courseId);
		collection.setUserId(userId);
		collection.setType(type);
		List<TCourseCollection> list = courseCollectionMapper.select(collection);
		if (!CollectionUtils.isEmpty(list)) {
			return list.get(0);
		}
		return null;
	}

	private TCourse selectById(Integer id) {
		TCourse course = new TCourse();
		course.setId(id);
		course.setIsDel(0);
		return courseMapper.selectOne(course);
	}
	
	/**
	 * 约课
	 * @param aboutVO
	 * @param userInfo
	 * @return
	 */
	@Override
	public  ResultVo<CourseAboutDto>  about(CourseAboutVO aboutVO, UserDto userInfo) {
		//拒绝订单不能继续约课
		TCourseBooked courseBooked = courseBookedService.selectById(aboutVO.getOrderId());
		if (courseBooked.getParticipate() == 0) {
			return ResultVo.failure("10005","该课已限制，你已无法继续约课！") ;
		}
		TCourseScheduleDetail detail = new TCourseScheduleDetail();
		detail.setId(aboutVO.getCourseSchId());
		detail = courseScheduleDetailMapper.selectByPrimaryKey(detail);
		Integer count =  courseAboutMapper.getUserAboutCount(detail.getStartTime(), detail.getEndTime(), userInfo.getId());
		if (count != null && count > 0) {
			return ResultVo.failure("10005","该时段已有约课信息") ;
			
		}
		//体验订单只能约课一次
		if (courseBooked.getSubType() == 1) {
			TCourseAbout tCourseAbout = new TCourseAbout();
			tCourseAbout.setUserId(userInfo.getId());
			tCourseAbout.setCourseId(Integer.parseInt(courseBooked.getCourseId()));
			tCourseAbout.setStatus(1);
			tCourseAbout.setOrderId(aboutVO.getOrderId());
			List<TCourseAbout> aboutList = courseAboutMapper.select(tCourseAbout);
			if (!CollectionUtils.isEmpty(aboutList)) {
				return ResultVo.failure("10005","体验订单只能约课一次") ;
			}
		}
		//判断约课时间是否过期
		Date endTime = detail.getEndTime();
		if (new Date().compareTo(endTime) > 0) {
			return ResultVo.failure("10005","排课已过期") ;
		}
		/*LocalDateTime now = LocalDateTime.now();
		LocalDateTime start = LocalDateTime.ofInstant(detail.getStartTime().toInstant(), ZoneId.systemDefault());
		if (now.compareTo(start.minusHours(24)) > 0) {
			return ResultVo.failure("10005", "距离开课时间不足24小时不可预约和取消约课");
		}*/
		TCourseBooked booked = courseBookedService.selectById(aboutVO.getOrderId());
		aboutVO.setCreateTime(new Date());
		aboutVO.setUserId(userInfo.getId());
		aboutVO.setCourseId(Integer.parseInt(booked.getCourseId()));
		TCourseAbout about = new TCourseAbout();
		BeanUtils.copyProperties(aboutVO, about);
		about.setStatus(1);
		about.setSubType(booked.getSubType());
		courseAboutMapper.insertSelective(about);
		CourseAboutDto result = new CourseAboutDto();
		BeanUtils.copyProperties(about, result);
		return ResultVo.success(result) ;
	}
	
	/**
	 * 我的约课
	 * @param userInfo
	 * @param status
	 * @param pageSize
	 * @param pageNum
	 * @return
	 */
	@Override
	public ResultPage<List<CourseAboutDto>> userAboutList(UserDto userInfo, Integer status, Integer pageSize, Integer pageNum) {
		PageInfo pageInfo = new PageInfo();
		pageInfo.setPageNum(pageNum == null ? 1 : pageNum);
		pageInfo.setPageSize(pageSize == null ? 10 : pageSize);

		Page<List<CourseAboutDto>> result = pageBuild(pageInfo).doSelectPage(() -> {
			courseAboutMapper.getUserAboutList(userInfo.getId(),status);
		});
		ResultPage resultPage = pageTransform(result);
		if (CollectionUtils.isEmpty(resultPage.getData())) {
			return resultPage;
		}
		List<CourseAboutDto> aboutList = resultPage.getData();
		List<Integer> courseIds = aboutList.stream().map(CourseAboutDto::getCourseId).collect(Collectors.toList());
		if (CollectionUtils.isEmpty(courseIds)) {
			return resultPage;
		}
		//查询约的课程列表
		List<TCourse> courses = this.selectByIdsAndType(courseIds);
		Map<Integer, CourseDto> courseMap = courses.stream().map(course->{
			CourseDto courseDto = new CourseDto();
			BeanUtils.copyProperties(course, courseDto);
			courseDto.setTitle(null);
			courseDto.setContent(null);
			return courseDto;
		}).collect(Collectors.toMap(CourseDto::getId, val -> val, (v1, v2) -> v1));

		aboutList = aboutList.stream().map(courseAboutDto -> {
			courseAboutDto.setCourseDto(courseMap.get(courseAboutDto.getCourseId()));
			if (new Date().compareTo(courseAboutDto.getEndTime()) > 0 && courseAboutDto.getStatus() != 0) {
				//已结束
				courseAboutDto.setStatus(2);
			}
			return courseAboutDto;
		}).collect(Collectors.toList());
		resultPage.setData(aboutList);
		return resultPage;
	}
	
	private List<TCourseScheduleDetail> selectScheduleList(List<Integer> schIds) {
		Example example = new Example(TCourseScheduleDetail.class);
		example.createCriteria().andIn("id", schIds);
		return courseScheduleDetailMapper.selectByExample(example);
	}
	
	/**
	 * 我的收藏
	 *
	 * @param type
	 * @param userId
	 * @return
	 */
	@Override
	public List<CourseDto> userCollectedList(String type, String userId) {
		List<CourseDto> result = new ArrayList<>();
		Example example = new Example(TCourseCollection.class);
		Example.Criteria criteria = example.createCriteria().andEqualTo("userId", userId);
		if (!StringUtils.isEmpty(type)) {
			criteria.andEqualTo("type",type);
		}
		example.setOrderByClause("createTime desc");

		List<TCourseCollection> collectionList = courseCollectionMapper.selectByExample(example);
		List<Integer> courseIds = collectionList.stream().map(TCourseCollection::getCourseId).collect(Collectors.toList());
		if (CollectionUtils.isEmpty(courseIds)) {
			return result;
		}
		//查询收藏的课程列表
		List<TCourse> courses = this.selectByIdsAndType(courseIds);
		return BeanMapperUtil.copyList(courses, CourseDto.class);
	}
	
	/**
	 * 订单列表
	 *
	 * @param type
	 * @param status
	 * @param pageSize
	 * @param pageNum
	 * @return
	 */
	@Override
	public ResultPage<List<CourseBookedDto>> userOrderList(String type, Integer status, String userId, Integer pageSize, Integer pageNum) {
		PageInfo pageInfo = new PageInfo();
		pageInfo.setPageNum(pageNum == null ? 1 : pageNum);
		pageInfo.setPageSize(pageSize == null ? 10 : pageSize);

		Example example = new Example(TCourseBooked.class);
		Example.Criteria criteria = example.createCriteria().andEqualTo("cuserId", userId);
		if (!StringUtils.isEmpty(type)) {
			criteria.andEqualTo("type",type);
		}
		if (status != null) {
			criteria.andEqualTo("status",status);
		}
		example.setOrderByClause("createTime desc");
		Page<List<TCourseBooked>> result = pageBuild(pageInfo).doSelectPage(() -> {
			courseBookedMapper.selectByExample(example);
		});
		ResultPage resultPage = pageTransform(result);
		if (CollectionUtils.isEmpty(resultPage.getData())) {
			return resultPage;
		}
		List<TCourseBooked> data = resultPage.getData();

		List<CourseBookedDto> orderList =  BeanMapperUtil.copyList(data, CourseBookedDto.class);
		List<String> courseIds = orderList.stream().map(CourseBookedDto::getCourseId).collect(Collectors.toList());
		List<TCourse> courses =  this.selectByIds(courseIds);
		if (CollectionUtils.isEmpty(courses)) {
			return resultPage;
		}
		Map<Integer, TCourse> courseMap = courses.stream().collect(Collectors.toMap(TCourse::getId, val -> val, (v1, v2) -> v1));
		orderList = orderList.stream().map(bookedDto -> {
			TCourse course = courseMap.get(Integer.parseInt(bookedDto.getCourseId()));
			if (course != null) {
				CourseDto courseDto = new CourseDto();
				BeanUtils.copyProperties(course, courseDto);
				courseDto.setContent(null);
				courseDto.setTitle(null);
				bookedDto.setCourseDto(courseDto);
			}
			if (null != bookedDto.getReferrerUser()){
				TUser tUser = new TUser();
				tUser.setInvitationCode(bookedDto.getReferrerUser());
				TUser newTUser = userMapper.selectOne(tUser);
				if (null != newTUser){
					UserDto userDto = new UserDto();
					BeanUtils.copyProperties(newTUser,userDto);
					bookedDto.setReUserDto(userDto);
				}
			}
			return bookedDto;
		}).collect(Collectors.toList());

		resultPage.setData(orderList);
		return resultPage;
	}
	
	private List<TCourse> selectByIds(List<String> courseIds) {
		Example example = new Example(TCourse.class);
		example.createCriteria().andEqualTo("isDel", 0).andIn("id", courseIds);
		return courseMapper.selectByExample(example);
	}
	
	private List<TCourse> selectByIdsAndType(List<Integer> courseIds) {
		Example example = new Example(TCourse.class);
		example.createCriteria().andEqualTo("isDel", 0).andIn("id", courseIds);
		return courseMapper.selectByExample(example);
	}
	
	/**
	 * 排课列表 v1
	 * @param userInfo
	 * @return
	 */
	@Override
	public List<CourseScheduleDetailDto> courseSchedule(CourseScheduleDetailVO courseScheduleDetailVO, UserDto userInfo) {
		/*TCourseScheduleDetail detail = new TCourseScheduleDetail();
		detail.setCourseId(courseId);
		List<TCourseScheduleDetail> scheduleDetails = courseScheduleDetailMapper.select(detail);
		List<Integer> seIds = scheduleDetails.stream().map(TCourseScheduleDetail::getId).collect(Collectors.toList());
		//查询约课信息
		Example example = new Example(TCourseAbout.class);
		Example.Criteria criteria = example.createCriteria()
				.andEqualTo("userId", userInfo.getId()).andIn("courseSchId",seIds);
		example.setOrderByClause("createTime desc");*/
		List<CourseScheduleDetailDto> scheduleDetailsDtoList  = courseAboutMapper.selectCourseScheduleList(courseScheduleDetailVO);
		for (CourseScheduleDetailDto sdetail:scheduleDetailsDtoList) {
			//状态，0=已过期，1=已预约，2=可预约
			sdetail.setStatus(2);
			if (new Date().compareTo(sdetail.getStartTime()) > 0) {
				sdetail.setStatus(0);
			}
			TCourseAbout tCourseAbout = new TCourseAbout();
			tCourseAbout.setCourseId(courseScheduleDetailVO.getCourseId());
			tCourseAbout.setCourseSchId(sdetail.getId());
			tCourseAbout.setUserId(userInfo.getId());
			tCourseAbout.setOrderId(courseScheduleDetailVO.getOrderId());
			tCourseAbout.setStatus(1);//已取消不管
			TCourseAbout newCourseAbout = courseAboutMapper.selectOne(tCourseAbout);
			if (null != newCourseAbout){
				sdetail.setStatus(1);
			}


			CourseVO courseVO = new CourseVO();
			courseVO.setId(courseScheduleDetailVO.getCourseId());
			CourseDto courseDto = courseMapper.selectCourseInfo(courseVO);
			// 设置无需返回参数
			courseDto.setAboutDtos(null);

			// 获取分类名称
			TSystemDictionary systemDictionary = dictMapper.selectSysDictInfo(courseDto.getClassifyId());
			courseDto.setClassifyName(systemDictionary.getName());
			// 返回课程/活动关联的师资
			List<CourseDto> teamList = courseMapper.selectTeam(courseScheduleDetailVO.getCourseId());
			if (null != teamList && teamList.size() > 0){
				courseDto.setTeamDto(teamList.get(0));
			}

			if (null != courseDto) {
				sdetail.setCourseDto(courseDto);
			}
		}
		return scheduleDetailsDtoList;
	}

	/**
	 * TODO: 多对多关系，待完善
	 * 获取排课列表
	 * @param courseScheduleDetailVO
	 * @param userInfo
	 * @return
	 */
	@Override
	public List<CourseScheduleDetailDto> courseScheduleList(CourseScheduleDetailVO courseScheduleDetailVO, UserDto userInfo) {
		List<CourseScheduleDetailDto> scheduleDetailDtoList = new ArrayList<CourseScheduleDetailDto>();
		for (String orderId:  courseScheduleDetailVO.getOrderIds().split(",")) {
			// 通过订单ID得到课程ID
			TCourseBooked courseBooked = new TCourseBooked();
			courseBooked.setId(Integer.valueOf(orderId));
			TCourseBooked newCourseBooked = courseBookedMapper.selectByPrimaryKey(courseBooked);

			// 设置课程ID
			courseScheduleDetailVO.setCourseId(Integer.valueOf(newCourseBooked.getCourseId()));
			List<CourseScheduleDetailDto> scheduleDetailsDtoList = courseAboutMapper.selectCourseScheduleList(courseScheduleDetailVO);
			for (CourseScheduleDetailDto sdetail : scheduleDetailsDtoList) {
				//状态，0=已过期，1=已预约，2=可预约
				sdetail.setStatus(2);
				if (new Date().compareTo(sdetail.getStartTime()) > 0) {
					sdetail.setStatus(0);
				}
				TCourseAbout tCourseAbout = new TCourseAbout();
				tCourseAbout.setCourseId(courseScheduleDetailVO.getCourseId());
				tCourseAbout.setCourseSchId(sdetail.getId());
				tCourseAbout.setUserId(userInfo.getId());
				tCourseAbout.setOrderId(courseScheduleDetailVO.getOrderId());
				tCourseAbout.setStatus(1);//已取消不管
				TCourseAbout newCourseAbout = courseAboutMapper.selectOne(tCourseAbout);
				if (null != newCourseAbout) {
					sdetail.setStatus(1);
				}


				CourseVO courseVO = new CourseVO();
				courseVO.setId(courseScheduleDetailVO.getCourseId());
				CourseDto courseDto = courseMapper.selectCourseInfo(courseVO);
				// 设置无需返回参数
				courseDto.setAboutDtos(null);

				// 获取分类名称
				TSystemDictionary systemDictionary = dictMapper.selectSysDictInfo(courseDto.getClassifyId());
				courseDto.setClassifyName(systemDictionary.getName());
				// 返回课程/活动关联的师资
				List<CourseDto> teamList = courseMapper.selectTeam(courseScheduleDetailVO.getCourseId());
				if (null != teamList && teamList.size() > 0) {
					courseDto.setTeamDto(teamList.get(0));
				}

				if (null != courseDto) {
					sdetail.setCourseDto(courseDto);
				}
				// 返回orderId
				sdetail.setOrderId(orderId);
				scheduleDetailDtoList.add(sdetail);
			}
		}
		return scheduleDetailDtoList;
	}
	
	/**
	 * 活动详情
	 * @param courseId
	 * @param userInfo
	 * @return
	 */
	@Override
	public CourseDto activityDetail(Integer courseId, UserDto userInfo) {
		CourseDto result = this.detail(courseId, userInfo);
		if (result.getSellBeginTime() != null && result.getSellEndTime() != null) {
			if (new Date().compareTo(result.getSellBeginTime()) < 0) {
				result.setActivityStatus(0);
			} else if (new Date().compareTo(result.getSellBeginTime()) > 0 && new Date().compareTo(result.getSellEndTime()) < 0) {
				result.setActivityStatus(1);
			} else if (new Date().compareTo(result.getSellEndTime()) > 0) {
				result.setActivityStatus(2);
			}
		}
		if (userInfo == null) {
			return result;
		}
		//判断是否可以免费报名
		List<TCourseDetail> codeByTypes = courseDetailService.getCodeByType(courseId, CourseDetailTypeEnum.COURSE.getType());
		if (CollectionUtils.isEmpty(codeByTypes)) {
			return result;
		}
		//获取关联的课程
		TCourseDetail detail = codeByTypes.get(0);
		String code = detail.getCode();
		TCourse course = this.selectById(Integer.parseInt(code));
		//判断是否购买了该课程
		CourseBookedDto courseBooke = courseBookedService.getUserCourseSuccessBooke(course.getId(), userInfo.getId());
		if (courseBooke != null && courseBooke.getStatus() == 2 && courseBooke.getSubType() != 1) {
			result.setFreeActivity(true);
		}
		
		return result;
	}

	/**
	 * 师资详情
	 * @param teamId
	 * @param userInfo
	 * @return
	 */
	@Override
	public CourseDto teamDetail(Integer teamId, UserDto userInfo) {
		CourseDto result = this.detail(teamId, userInfo);
		if (userInfo == null) {
			return result;
		}
		return result;
	}
	
	/**
	 * 课程活动详情
	 * @param courseId
	 * @param userInfo
	 * @return
	 */
	private CourseDto detail(Integer courseId, UserDto userInfo){
		TCourse course = new TCourse();
		course.setId(courseId);
		course = courseMapper.selectOne(course);
		CourseDto result = new CourseDto();
		BeanUtils.copyProperties(course, result);
		result.setCover(ImageUtil.getImgUrl(result.getCover()));

		// 获取分类名称
		TSystemDictionary systemDictionary = dictMapper.selectSysDictInfo(course.getClassifyId());
		result.setClassifyName(systemDictionary.getName());

		// 返回活动关联的课程
		if (null != course.getType() && course.getType().equals("activity")){
			List<CourseDto> courseDtoList = courseMapper.selectActityCourseList(courseId);
			if (null != courseDtoList && courseDtoList.size() > 0){
				result.setCourseDtoList(courseDtoList);
			}
		}
		// 返回课程/活动关联的师资
		if(null != course.getType() && (course.getType().equals("course") || course.getType().equals("activity"))) {
			List<CourseDto> teamList = courseMapper.selectTeam(courseId);
			if (null != teamList && teamList.size() > 0){
				result.setTeamDto(teamList.get(0));
			}
		}

		if (!StringUtils.isEmpty(result.getImgs())) {
			result.setImgs(Arrays.stream(result.getImgs().split(",")).map(ImageUtil::getImgUrl).collect(Collectors.joining(",")));
		}
		//查询客服信息
		TCorporate corporate = corporateService.getInfo();
		if (corporate != null) {
			result.setCorporateMobile(corporate.getPhone1());
			result.setCorporateWechatId(corporate.getWechatId());
		}
		//是否可以体验预约
		if (userInfo != null && !course.getType().equals("team")) {
			//Integer userBookeCount = courseBookedService.getUserFreeBookeCount(userInfo.getId());
			if (userInfo.getFreeNum() != null && userInfo.getFreeNum() > 0) {
				result.setFree(true);
			}
			//订单信息
			CourseBookedDto bookedDto = courseBookedService.getUserCourseBookeSubType(courseId, userInfo.getId());
			if (bookedDto != null || course.getSaleNum() >= course.getLimitStuNum()) {
				result.setCanBuy(false);
			}
			//是否收藏
			TCourseCollection collection = this.selectCollect(userInfo.getId(), result.getId(), result.getType());
			if (collection != null) {
				result.setCollected(1);
			}
			//记录浏览信息
			this.saveBowseInfo(course, userInfo.getId());
		}
		return result;
	}

	/**
	 * 记录浏览信息
	 * @param course
	 * @param userId
	 */
	private void saveBowseInfo(TCourse course, String userId) {
		TBrowseRecord record = new TBrowseRecord();
		record.setCourseId(course.getId());
		record.setUserId(userId);
		record.setType(course.getType());
		List<TBrowseRecord> recordList = browseRecordMapper.select(record);
		if (CollectionUtils.isEmpty(recordList)) {
			//新增
			record.setLastBrowseTime(new Date());
			record.setTotal(1);
			browseRecordMapper.insertSelective(record);
		}else {
			//更新
			TBrowseRecord browseRecord = recordList.get(0);
			browseRecord.setLastBrowseTime(new Date());
			browseRecord.setTotal(browseRecord.getTotal() + 1);
			browseRecordMapper.updateByPrimaryKeySelective(browseRecord);
		}
	}

	/**
	 * 订单详情
	 * @param orderId
	 * @param userInfo
	 * @return
	 */
	@Override
	public CourseBookedDto orderDetail(Integer orderId, UserDto userInfo) {
		TCourseBooked booked = courseBookedService.selectById(orderId);
		if (booked == null) {
			return null;
		}
		CourseBookedDto result = new CourseBookedDto();
		BeanUtils.copyProperties(booked, result);
		TCourse course = this.selectById(Integer.parseInt(booked.getCourseId()));
		if (course != null) {
			CourseDto courseDto = new CourseDto();
			BeanUtils.copyProperties(course, courseDto);
			result.setCourseDto(courseDto);
			
		}
		if (null != result.getReferrerUser()){
			TUser tUser = new TUser();
			tUser.setInvitationCode(result.getReferrerUser());
			TUser newTUser = userMapper.selectOne(tUser);
			if (null != newTUser){
				UserDto userDto = new UserDto();
				BeanUtils.copyProperties(newTUser,userDto);
				result.setReUserDto(userDto);
			}
		}
		return result;
	}
	
	/**
	 * 用户权益
	 * @param userInfo
	 * @return
	 */
	@Override
	public List<CourseDto> userRights(UserDto userInfo) {
		List<TCourseBooked> courseBookeds = courseBookedService.getUserCourseBookeList(userInfo.getId(),2);
		if (CollectionUtils.isEmpty(courseBookeds)) {
			return new ArrayList<>();
		}
		courseBookeds = courseBookeds.stream()
				.filter(val -> "course".equals(val.getType()))
				.filter(val -> filterFreeRights(val)).collect(Collectors.toList());
		//权益只获取课程
		List<String> courseIds = courseBookeds.stream().map(TCourseBooked::getCourseId).collect(Collectors.toList());
		List<TCourse> courses = this.selectByIds(courseIds);
		Map<Integer, TCourse> courseMap = courses.stream().collect(Collectors.toMap(TCourse::getId, val -> val));
		List<CourseDto>  result = courseBookeds.stream().map(booked -> {
			CourseDto courseDto = new CourseDto();
			TCourse course = courseMap.get(Integer.parseInt(booked.getCourseId()));
			if (course != null) {
				BeanUtils.copyProperties(course, courseDto);
				courseDto.setOrderId(booked.getId());
			}
			return courseDto;
		}).sorted(Comparator.comparing(CourseDto::getOrderId).reversed()).collect(Collectors.toList());
		return result;
	}

	private boolean filterFreeRights(TCourseBooked booked) {
		Boolean result = true;
		//体验订单需要去过滤约课，体验订单【体验订单必须是已经约了时间，并且该时间已过 才移除
		//如果体验订单从未预约时间或者预约了时间还没达到结束时段不移除
		if (booked.getSubType() != 1) {
			return result;
		}
		//查询有没有约课
		TCourseAbout about = new TCourseAbout();
		about.setOrderId(booked.getId());
		about.setStatus(1);
		List<TCourseAbout> aboutList = courseAboutMapper.select(about);
		if (CollectionUtils.isEmpty(aboutList)) {
			return result;
		}
		about = aboutList.get(0);
		//判断约课是否过期
		TCourseScheduleDetail detail = new TCourseScheduleDetail();
		detail.setId(about.getCourseSchId());
		detail = courseScheduleDetailMapper.selectByPrimaryKey(detail);
		if (detail != null && new Date().compareTo(detail.getEndTime()) > 0) {
			result = false;
		}
		return result;
	}

	@Override
	public CourseDto updateCourse(CourseVO courseVO, UserDto userInfo) {
		if (null != courseVO && null != courseVO.getId()){
			CourseDto courseDto = courseMapper.selectCourseInfo(courseVO);
			if (null != courseDto){
				TCourse tCourse = new TCourse();
				BeanUtils.copyProperties(courseVO,tCourse);
				tCourse.setUpdateTime(new Date());
				tCourse.setUpdateUserId(userInfo.getId());
				int updateCourse = courseMapper.updateByPrimaryKeySelective(tCourse);
				if (updateCourse > 0){
					BeanUtils.copyProperties(courseDto,tCourse);
					//活动关联课程
					if (courseDto.getType().equals("activity") && null != courseVO.getCourseList() && courseVO.getCourseList().size() > 0){
						//删除关联的课程
						TCourseDetail tCourseDetail = new TCourseDetail();
						tCourseDetail.setCourseId(tCourse.getId());
						courseDetailMapper.delete(tCourseDetail);
						for (CourseVO newCourseVO:courseVO.getCourseList()) {
							TCourseDetail newTCourseDetail = new TCourseDetail();
							newTCourseDetail.setCourseId(tCourse.getId());
							newTCourseDetail.setCode(newCourseVO.getId()+"");
							newTCourseDetail.setType("course");
							newTCourseDetail.setCreateTime(new Date());
							newTCourseDetail.setCreateUserId(userInfo.getId());
							int newAddCourseDetail = courseDetailMapper.insertSelective(newTCourseDetail);
						}
					}

					// 课程｜活动关联师资
					if ((courseDto.getType().equals("activity") || courseDto.getType().equals("course"))  && null!= courseVO.getTeamId() && courseVO.getTeamId() > 0){
						//删除关联的课程
						TCourseDetail tTeamDetail = new TCourseDetail();
						tTeamDetail.setCourseId(tCourse.getId());
						courseDetailMapper.delete(tTeamDetail);


						TCourseDetail newTeamDetail = new TCourseDetail();
						// 生成的课程ID
						newTeamDetail.setCourseId(tCourse.getId());
						// 绑定的师资ID
						newTeamDetail.setCode(courseVO.getTeamId()+"");
						newTeamDetail.setType("team");
						newTeamDetail.setCreateTime(new Date());
						newTeamDetail.setCreateUserId(userInfo.getId());
						int newAddCourseDetail = courseDetailMapper.insertSelective(newTeamDetail);

					}

					return courseDto;
				}
			}
		}

		return null;
	}

	@Override
	public boolean updateCourseStatus(List<CourseVO> courseVOList, int status, UserDto userInfo) {
		if (null != courseVOList && courseVOList.size() > 0){
			for (CourseVO courseVO:courseVOList) {
				TCourse tCourse = new TCourse();
				tCourse.setId(courseVO.getId());
				//状态 1:生效 0:未生效 2:下架
				tCourse.setStatus(status);
				tCourse.setUpdateTime(new Date());
				tCourse.setUpdateUserId(userInfo.getId());
				int updateCourse = courseMapper.updateByPrimaryKeySelective(tCourse);
				if (updateCourse <= 0){
					System.out.println("上架失败：" + courseVO.getId());
				}
			}
			return true;
		}
		return false;
	}

	/**
	 * 删除课程
	 * @param courseVO
	 * @param userInfo
	 * @return
	 */
	@Override
	public Boolean deleteCourse(CourseVO courseVO, UserDto userInfo) {
		if (null != courseVO && null != courseVO.getId()){
			TCourse tCourse = new TCourse();
			tCourse.setId(courseVO.getId());
			tCourse.setIsDel(1);
			tCourse.setUpdateTime(new Date());
			tCourse.setUpdateUserId(userInfo.getId());
			int updateCourse = courseMapper.updateByPrimaryKeySelective(tCourse);
			if (updateCourse > 0){
				return true;
			}
		}
		return false;
	}
	
	/**
	 * 统计用户购买的课程和活动量
	 * @param userIds
	 * @return
	 */
	@Override
	public List<UserCountDto> selectCountByUsers(List<String> userIds) {
		if (CollectionUtils.isEmpty(userIds)) {
			return new ArrayList<>();
		}
		return courseMapper.selectCountByUsers(userIds);
	}
	
	@Override
	public List<UserCountDto> countUserAbout(List<String> userIds) {
		if (CollectionUtils.isEmpty(userIds)) {
			return new ArrayList<>();
		}
		return courseMapper.countUserAbout(userIds);
	}

	/**
	 * 查询课程排课时间列表
	 * @param courseScheduleDetailVO
	 * @return
	 */
	@Override
	public List<CourseScheduleDetailDto> selectCourseScheduleList(CourseScheduleDetailVO courseScheduleDetailVO) {
		List<CourseScheduleDetailDto> list = courseScheduleDetailMapper.selectCourseScheduleList(courseScheduleDetailVO);
		return list;
	}

	@Override
	public ResultVo<CourseScheduleDetailDto> putCourseSchedule(CourseScheduleDetailVO courseScheduleDetailVO, UserDto userInfo) {
		if (null != courseScheduleDetailVO){
			if (null != courseScheduleDetailVO.getId()){
				//修改
				int oldScheduleCount = courseScheduleDetailMapper.getOldScheduleCount(courseScheduleDetailVO);
				if (oldScheduleCount > 0){
					return ResultVo.failure("10008","该时间段已有课程");
				}
				TCourseScheduleDetail tCourseScheduleDetail = new TCourseScheduleDetail();
				BeanUtils.copyProperties(courseScheduleDetailVO,tCourseScheduleDetail);
				tCourseScheduleDetail.setUpdateTime(new Date());
				tCourseScheduleDetail.setUpdateUserId(userInfo.getId());
				int updateCourseSchedule = courseScheduleDetailMapper.updateByPrimaryKeySelective(tCourseScheduleDetail);
				if (updateCourseSchedule > 0){
					CourseScheduleDetailDto courseScheduleDetailDto = new CourseScheduleDetailDto();
					BeanUtils.copyProperties(tCourseScheduleDetail,courseScheduleDetailDto);
					return ResultVo.success(courseScheduleDetailDto);
				}
			}else {
				//新增
				int oldScheduleCount = courseScheduleDetailMapper.getOldScheduleCount(courseScheduleDetailVO);
				if (oldScheduleCount > 0){
					return ResultVo.failure("10008","该时间段已有课程");
				}
				TCourseScheduleDetail tCourseScheduleDetail = new TCourseScheduleDetail();
				BeanUtils.copyProperties(courseScheduleDetailVO,tCourseScheduleDetail);
				tCourseScheduleDetail.setCreateTime(new Date());
				tCourseScheduleDetail.setCreateUserId(userInfo.getId());
				tCourseScheduleDetail.setUpdateTime(new Date());
				tCourseScheduleDetail.setUpdateUserId(userInfo.getId());
				int insertCourseSchedule = courseScheduleDetailMapper.insertSelective(tCourseScheduleDetail);
				if (insertCourseSchedule > 0){
					CourseScheduleDetailDto courseScheduleDetailDto = new CourseScheduleDetailDto();
					BeanUtils.copyProperties(tCourseScheduleDetail,courseScheduleDetailDto);
					return ResultVo.success(courseScheduleDetailDto);
				}

			}
		}
		return null;
	}

	/**
	 * 删除排课
	 * @param courseScheduleDetailVO
	 * @return
	 */
	@Override
	public ResultVo<Boolean> deleteCourseSchedule(CourseScheduleDetailVO courseScheduleDetailVO) {
		if (null != courseScheduleDetailVO && null != courseScheduleDetailVO.getId()){
			int aboutCount = courseAboutMapper.getAboutCount(courseScheduleDetailVO.getId());
			if (aboutCount > 0){
				return ResultVo.failure("10007","该课次下面已经有学员预约，不能删除该课次！");
			}
			TCourseScheduleDetail tCourseScheduleDetail = new TCourseScheduleDetail();
			tCourseScheduleDetail.setId(courseScheduleDetailVO.getId());
			int delete = courseScheduleDetailMapper.delete(tCourseScheduleDetail);
			if (delete > 0){
				return ResultVo.success(true);
			}
		}
		return null;
	}

	/**
	 * 订单审核
	 * @param bookedVO
	 * @param userInfo
	 * @return
	 */
	@Override
	public CourseBookedDto orderAudit(CourseBookedVO bookedVO, UserDto userInfo) {
		TCourseBooked booked = new TCourseBooked();
		booked.setId(bookedVO.getId());
		booked.setStatus(bookedVO.getStatus());
		booked.setUpdateUserId(userInfo.getId());
		booked.setUpdateTime(new Date());
		courseBookedMapper.updateByPrimaryKeySelective(booked);
		booked = new TCourseBooked();
		booked.setId(bookedVO.getId());
		CourseBookedDto result = new CourseBookedDto();
		BeanUtils.copyProperties(courseBookedMapper.selectOne(booked), result);
		return result;
	}

	/**
	 * 获取课程浏览用户列表
	 * @param browseRecordVO
	 * @return
	 */
	@Override
	public ResultPage<List<BrowseRecordDto>> selectCourseBrowseList(BrowseRecordVO browseRecordVO) {
		PageInfo pageInfo = new PageInfo();
		pageInfo.setPageNum(browseRecordVO.getPageNum());
		pageInfo.setPageSize(browseRecordVO.getPageSize());
		Page<List<BrowseRecordDto>> reslut = pageBuild(pageInfo).doSelectPage(()->{
			List<BrowseRecordDto> list = courseMapper.selectCourseBrowseList(browseRecordVO);
			for (BrowseRecordDto browseRecordDto:list) {
				int coursePayNum = courseMapper.getCoursePayNumByUser(browseRecordDto.getCourseId(),browseRecordDto.getUserId());
				if (coursePayNum > 0){
					browseRecordDto.setIsPay(1);
				}else {
					browseRecordDto.setIsPay(0);
				}
				if (null != browseRecordDto.getUserId()){
					TUser tUser = new TUser();
					tUser.setId(browseRecordDto.getUserId());
					TUser newTUser = userMapper.selectOne(tUser);
					if (null != newTUser){
						UserDto userDto = new UserDto();
						BeanUtils.copyProperties(newTUser,userDto);
						browseRecordDto.setUserDto(userDto);
					}
				}
			}
		});
		return pageTransform(reslut);
	}

	/**
	 * 取消约课
	 * @param aboutVO
	 * @param userInfo
	 * @return
	 */
	@Override
	public ResultVo cancelAbout(CourseAboutVO aboutVO, UserDto userInfo) {
		//课程开始24小时内不可取消
		TCourseAbout about = new TCourseAbout();
		about.setId(aboutVO.getId());
		about = courseAboutMapper.selectByPrimaryKey(about);
		if (null != about){
			TCourseScheduleDetail detail = new TCourseScheduleDetail();
			detail.setId(about.getCourseSchId());
			detail = courseScheduleDetailMapper.selectByPrimaryKey(detail);
			if (null != detail){
				Date startTime = detail.getStartTime();
				LocalDateTime start = LocalDateTime.ofInstant(startTime.toInstant(), ZoneId.systemDefault());
				long between = ChronoUnit.HOURS.between(LocalDateTime.now(),start);
				if (between < 24) {
					return ResultVo.failure("10005","开课前24小时内不可取消预约");
				}
				about.setStatus(aboutVO.getStatus());
				courseAboutMapper.updateByPrimaryKeySelective(about);
				return ResultVo.success();
			}
		}
		return ResultVo.failure("10003","操作失败。");
	}
}
